package org.swift.mashup.engine.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class ActivitySet implements Activity {

	private final Map<String, Collection<Activity>> activities = new HashMap<String, Collection<Activity>>();

	public ActivitySet() {
	}

	public ActivitySet(final Map<String, Collection<Activity>> activities) {
		this.activities.putAll(activities);
	}

	public void addActivity(final String name, final Activity activity) {
		if (activities.containsKey(name)) {
			activities.get(name).add(activity);
		} else {
			Collection<Activity> activityList = new ArrayList<Activity>();
			activityList.add(activity);
			activities.put(name, activityList);
		}
	}

	@Override
	public ActivityResultComponent doActivity(ActivityContext context,
			Map<String, ? extends Object> parameters) throws ActivityException {
		final ActivityResultComponent activityResultItems = new ActivityResultGroup();

		if ( context instanceof InputStreamActivityContext && hasMultipleActivities() ) {
			try {
				context = new ByteArrayActivityContext(context.getBytes());
			}
			catch (IOException e) {
				throw new ActivityException("Failed to convert InputStreamActivityContext to ByteArrayActivityContext", e);
			}
		}

		for (Entry<String, Collection<Activity>> entry : activities.entrySet()) {
			String type = entry.getKey();
			for (Activity activity : entry.getValue()) {
				ActivityResultComponent resultComponent = activity.doActivity(
					context, parameters);
				resultComponent.setType(type);
				activityResultItems.add(resultComponent);
			}
		}
		return activityResultItems;
	}

	protected boolean hasMultipleActivities() {
		if ( activities.size() > 1 ) {
			return true;
		}

		for (Collection<Activity> collection : activities.values()) {
			if ( collection.size() > 1 ) {
				return true;
			}
		}

		return false;
	}
}
